<?php

App::uses('CrawlUtility', 'Utility');

class OriginalArticlesController extends AppController{
	
	var $name = 'OriginalArticles';
	
	
	public function admin_sync() {
		$url = 'http://www.hunwater.com/api/article';
		$this->loadModel('Wx');
		$page=1;
		do{
		    $url = 'http://www.hunwater.com/api/article?page='.$page;
		    //$url = 'http://test.www.hunwater.com:20080/api/article?page='.$page;
		    $content = CrawlUtility::getRomoteUrlContent($url);
		    $result = json_decode($content,true);
		    foreach($result['data']['article']  as $article){
		        unset($article['content']);
		        if(!isset($article['url'])){
		            continue;
		        }
		        $hasget = $this->OriginalArticle->find('first',array(
		            'conditions' => array('remoteurl'=>$article['url'])
		        ));
		        if(!empty($hasget)) {
		            break;
		        }
		        
	            $urlinfo = parse_url($article['url']);
	            parse_str($urlinfo['query'],$query);
	            $biz = $query['__biz'];
		        $slug = $article['pub_id'];
		        if(empty($slug) || empty($biz)) {
		            continue;
		        }
		        $wxinfo = $this->Wx->find('first',array('conditions'=>array(
		            'OR'=> array('biz'=>$biz,'slug'=>$slug)
		        )));
		        if(empty($wxinfo)) {
		            $this->Wx->save(array(
		                'slug' => $slug,
		                'biz' => $biz,
		                'name' => $article['name'],
		            ));
		            $wx_id = $this->Wx->getLastInsertID();
		        }
		        else{
		            $wx_id = $wxinfo['Wx']['id'];
		        }
		        $this->OriginalArticle->create();
		        $this->OriginalArticle->save(array(
		            'name' => $article['title'],
		            'coverimg' => $article['front_pic'],
		            'summary' => $article['msg_desc'],
		            'created' => $article['pubtime'],
		            'author' => $article['author'],
		            'is_virtual' => 1,
		            'remoteurl' => $article['url'],
		            'view_nums' => $article['read_num'],
		            'wx_id' => $wx_id,
		        ));
		    }
		    $page++;
		}while( count($result['data']['article']) == $result['data']['page_size'] );
		
	}
	
	
}